<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>next方法的参数</title>
</head>
<body>
    <h1>next方法的参数</h1>
    <h2>next方法可以带一个参数，该参数会被当作上一个yield表达式的返回值</h2>

    <script>
        // next方法的参数示例
        function* foo(x) {
            const y = 2 * (yield (x + 1));
            const z = yield (y / 3);
            return (x + y + z);
        }

        const a = foo(5);
        console.log(a.next()); // {value: 6, done: false}
        console.log(a.next(12)); // {value: 8, done: false}
        console.log(a.next(13)); // {value: 42, done: true}

        // 使用next参数实现输入输出
        function* dataProcessor() {
            console.log('开始处理数据');
            const result1 = yield '请输入第一个数字';
            console.log('第一个数字:', result1);
            const result2 = yield '请输入第二个数字';
            console.log('第二个数字:', result2);
            return result1 + result2;
        }

        const processor = dataProcessor();
        console.log(processor.next()); // 开始处理数据
        console.log(processor.next(100)); // 第一个数字: 100
        console.log(processor.next(200)); // 第二个数字: 200, 返回300

        // 使用next参数改变Generator函数内部状态
        function* counter(value) {
            while(true) {
                const step = yield value;
                if (step) {
                    value += step;
                } else {
                    value++;
                }
            }
        }

        const generatorCounter = counter(0);
        console.log(generatorCounter.next().value); // 0
        console.log(generatorCounter.next(10).value); // 10
        console.log(generatorCounter.next(2).value); // 12
        console.log(generatorCounter.next().value); // 13
    </script>
</body>
</html> 